package com.uw.uwrpc.core.consumer.invoker;

import com.alibaba.fastjson.JSON;
import com.uw.uwrpc.core.api.RpcRequest;
import com.uw.uwrpc.core.api.RpcResponse;
import com.uw.uwrpc.core.consumer.ConsumerInvoker;
import com.uw.uwrpc.core.exception.ErrorCode;
import com.uw.uwrpc.core.exception.RpcException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpConsumerInvoker implements ConsumerInvoker {
    private final OkHttpClient client;

    public HttpConsumerInvoker(long readTimeout, long writeTimeout, long connectTimeout) {
        client = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(16, 60, TimeUnit.SECONDS))
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    @Override
    public RpcResponse<?> invoke(RpcRequest rpcRequest, String url) {
        return post(rpcRequest, url);
    }

    private RpcResponse<?> post(RpcRequest rpcRequest, String url) {
        log.debug("===> url:" + url);
        log.debug("===> RpcRequest:" + rpcRequest);
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON.toJSONString(rpcRequest), MediaType.get("application/json; charset=utf-8")))
                .build();

        try (Response response = client.newCall(request).execute();) {
             ResponseBody body = response.body();
            RpcResponse<?> rpcResponse = JSON.parseObject(body.string(), RpcResponse.class);
            log.debug("===> RpcResponse:" + rpcResponse);
            return rpcResponse;
        } catch (IOException e) {
            if (e instanceof SocketTimeoutException ex) {
                throw new RpcException(ErrorCode.socket_timeout, e);
            }
            throw new RpcException(e);
        }

    }
}
